package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true) //将dishCache名下  所有缓存数据删除
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        /*//清理当前添加菜品分类下的缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //1.构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //1.1条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //1.2条件过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //1.3添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //1.4执行分页查询
        dishService.page(pageInfo, queryWrapper);

        //2. 创建新的分页对象
        Page<DishDto> dtoPage = new Page<>(); //不需要查询数据库  不需要添加分页参数
        //3.进行对象拷贝
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        //4.获取基本分页查询的集合数据
        List<Dish> records = pageInfo.getRecords();
        ArrayList<DishDto> dtoArrayList = new ArrayList<>();
        //5.遍历菜品集合
        records.forEach(dish -> {
            //5.1 将Dish拷贝到DishDto
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(dish, dto);
            //5.2 查询每一个菜品所属分类名称
            Category c = categoryService.getById(dish.getCategoryId());
            if (c != null) {
                dto.setCategoryName(c.getName());
            }
            //5.3放入集合中
            dtoArrayList.add(dto);
        });
        //6. 将dtoArrayList 添加到dtoPage中
        dtoPage.setRecords(dtoArrayList);
        //7.返回对象分页数据
        return R.success(dtoPage);

    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true) //将dishCache名下  所有缓存数据删除
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);

        //清理所有菜品的缓存数据
        /*Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys);*/

        //清理当前添加菜品分类下的缓存
        /*String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
*/

        return R.success("修改成功");
    }

    /**
     * 根据条件  查询对应的菜品信息
     *
     * @param dish
     * @return
     */
//    @GetMapping("/list")
//    public R<List<Dish>> list(Dish dish){
//        //构造查询条件
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
//        // 添加条件  查询状态为1(起售状态)的菜品
//        queryWrapper.eq(Dish::getStatus,1);
//        //添加排序条件
//        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
//        List<Dish> list = dishService.list(queryWrapper);
//        return R.success(list);
//    }
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId+'_'+#dish.status")
    public R<List<DishDto>> list(Dish dish) {

        //List<DishDto> dishDtoList;
        //动态构造key
        /*String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if (dishDtoList != null) {
            //如果存在  直接返回  无需查询数据库
            return R.success(dishDtoList);
        }*/


        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        // 添加条件  查询状态为1(起售状态)的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = new ArrayList<>();
        list.forEach(item -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();//查询菜品口味信息
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        });
        //如果不存在 需要查询数据库 将查询到的菜品数据 存到redis
        //redisTemplate.opsForValue().set(key, dishDtoList1, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",allEntries = true) // 删除dishCache名下 所有缓存数据
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        dishService.deleteDish(ids);


        //清理当前添加菜品分类下的缓存
        /*String key = "dish_" +ids + "_1";
        redisTemplate.delete(key);*/
        //清理所有菜品的缓存数据
        /*Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys);*/

        return R.success("删除成功!");
    }


    /**
     * 批量起售停售菜品
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable Integer status, @RequestParam List<Long> ids) {
        log.info("status:{}", status);
        log.info("ids:{}", ids);

        dishService.updateBatchStatus(status, ids);

        return R.success("菜品状态修改成功");
    }
}
